// Copyright (c) 2024, cy080585@126.com and contributors
// For license information, please see license.txt

frappe.ui.form.on("Packing Process", {
	

    setup:function(frm){

        // 给联系人和地址设置限制条件，得与 refresh 中的 frappe.dynamic_link = { doc: frm.doc, fieldname: "customer", doctype: "Customer" }; 的配合使用
        frm.set_query("customer_address", erpnext.queries.address_query);
        frm.set_query("contact_person", erpnext.queries.contact_query);

    },
    // 取消关联单据
    onload: function(frm) {
        // Ignore cancellation for all linked documents of respective DocTypes.
        frm.ignore_doctypes_on_cancel_all = ["Packing List", "Packing List Item"];
        if(frm.doc.docstatus!=0){
            frm.set_df_property('data_import','hidden', 1)
        }
        if(frm.doc.total_amount===frm.doc.total_amount_paid){
            frm.set_df_property("payment_amount", "hidden", 1)
        }
        
    },
    
    refresh(frm){
        // 此句目的是给地址和联系人添加动态链接的限制条件
        frappe.dynamic_link = { doc: frm.doc, fieldname: "customer", doctype: "Customer" };

        if (frm.doc.docstatus==1)
        {
           frappe.call({
                    method:"zy_packlist.zy_packlist.doctype.packing_process.packing_process.get_packing_process_details",
                    args:{
                        packing_name:frm.doc.name,
                        as_dict:true
                    },
                    callback:function(r){
                        console.log(r);
                        if(r.message){
                        console.log(r.message)
                        frappe.erpnext_excel.download_excel_single(frm,r.message)
                        }
                    }
           })
        } 

        if(frm.doc.docstatus!=1){
            frm.set_df_property('data_import','hidden', 0)
        }
        if(frm.doc.docstatus===1 &&frm.doc.is_freeze===0 &&(frappe.user.has_role("Customs Broker") || frappe.user.has_role("System Manager"))){
            frm.add_custom_button('Freeze', () => {
                frappe.call({
                    method:"zy_packlist.zy_packlist.doctype.packing_process.packing_process.freeze_packing_process",
                    args:{
                        name:frm.doc.name,
                    },
                    callback:function(r){
                        frappe.msgprint(__('Packing Process has been frozen successfully.'))
                    }
                })
            });
        }

       },

       display_item(frm) {
        frappe.call({
            method:"zy_packlist.zy_packlist.doctype.packing_process.packing_process.get_packing_process_details",
            args:{
                packing_name:frm.doc.name
            },
            callback:function(r){
                console.log(r);
                let head_data=[[__('Marks No.'), 'Item code', 'Descriptions', 'Size/pc (INCH)','Customs Item Code','Quantities','UOM','Rate','Amount','Net Weight(Kg)/ Sets','Net Weight(Kg)','Gross Weight(Kg)','CTNS','Carton Measure (CM)','CBM']]
                erpnext.disply_items(head_data,r.message.items,[0,10,11,12,13,14])
            }
       });

    },


    data_import(frm){

        if (frm.doc.customer && frm.is_new()){
            f_method='zy_packlist.zy_packlist.doctype.packing_order.packing_order.import_parking_order'
            new erpnext.PackingListFile(f_method,(r)=>{
 
                    const savePromises = r.table_head.map(element => {  
                        let row = frm.add_child('items', {  
                            marks_no: element.marks_no,  
                            net_weight_pkg: element.net_weight_pkg,  
                            gross_weight_pkg: element.gross_weight_pkg,  
                            packages_no: element.packages_no,  
                            carton_measure: element.carton_measure,  
                            cbm: element.cbm,  
                        });          
                        return frappe.call({  
                            method: "zy_packlist.zy_packlist.doctype.packing_list.packing_list.add_packing_items_ledgers",  
                            args: {  
                                entries: r.table_body[element.marks_no],  
                                child_row: row,  
                                doc: frm.doc  
                            }  
                        }).then(r => {  
                            let update_values = {  
                                "packing_list_items": r.message.name,  
                                "net_weight_pkg": r.message.net_weight_pkg,  
                                "old_packing_list_items": r.message.name,
                                "qty":r.message.total_qty,
                                "amount":r.message.total_amount,
                            };  
                            frappe.model.set_value(row.doctype, row.name, update_values);  
                        });  
                    });  
                    
                    Promise.all(savePromises).then(() => {  
                        frm.save();  
                        frm.refresh_field('items');
                    });          
            })

        }else{
            frappe.msgprint(__("No customer selected or document not in new status"));
        }
        
    },

    customer(frm){
        erpnext.utils.get_party_details(frm, null, null, null);
    },
    customer_address(frm){
        erpnext.customer_address_display(frm, "customer_address","address_display");
    },

    contact_person(frm){
        // erpnext.customer_contact_display(frm, "contact_person", "contact_display");
        erpnext.utils.get_contact_details(frm);
    },
    

    after_save(frm){
        if(!frm.doc.invoice_no){
            frm.set_value("invoice_no",frm.doc.name);
            // console.log('wozhixingle')
            frm.dirty()
            frm.save();
        }    
    },

    before_submit(frm){
        frm.doc.items.forEach(element => {
            if(!element.packing_list_items){
                frappe.throw(__("Please maintain material detail data,line number is ")+element.idx);
            }
        });
    },


});


frappe.ui.form.on("Packing Process Item", {

    get_items(frm, cdt, cdn){
        let item = locals[cdt][cdn];
        new erpnext.PackingListItems(
            frm, item,(r) => {
                if (r) {
                    console.log("woshicallback");
                    console.log(r);
                    let update_values = {
                        "packing_list_items": r.name,
                         "net_weight_pkg":r.net_weight_pkg,
                         "old_packing_list_items":r.name,
                         "qty":r.total_qty,
                        "amount":r.total_amount,
                    }
                    // console.log('item.doctype---'+item.doctype +'item.name---'+item.name +'update_values--'+update_values)
                    frappe.model.set_value(item.doctype, item.name, update_values);
                }
            }
        );

    },

    carton_measure(frm, cdt, cdn){
        let row=locals[cdt][cdn];
        if(row.carton_measure){
            const regex = /^\d+\*\d+\*\d+$/;
           if( regex.test(row.carton_measure)){
            
            const regex_out = /\d+/g; 
            let values = row.carton_measure.match(regex_out);
            let cbm = 1;
            values.forEach(element => {
                cbm*=element;
            });
            frappe.model.set_value(row.doctype, row.name, "cbm", cbm/1000000);
           }
           else{
            frappe.msgprint("Invalid format for carton measure. Please use like 100*200*300");
           }         
        }
    },


    gross_weight_pkg(frm, cdt, cdn){
        let row=locals[cdt][cdn];
        if(row.gross_weight_pkg<row.net_weight_pkg){
            frappe.msgprint("The gross weight must be greater than the net weight");
            row.gross_weight_pkg=0;
       }
    },



});
